package dao

import (
	"errors"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"net/http"
	"time"
)

/**
Session
*/
type GuestSession AdminUserLogin

//init
func (gs *GuestSession) Init(r *http.Request) *GuestSession {

	//启动Redis建立连接
	InitRedis()

	guestId, err := r.Cookie("guestId")
	if err != nil || guestId == nil {
		//随机生成
		gs.Key = Md5(time.Now().Format(TimeLayout) + "|" + GetRandomString(8))
	} else {
		gs.Key = guestId.Value
		err = gs.GetSession()
		if err != nil {
			LogError(err)
			return new(GuestSession)
		}

	}

	if gs.Key == "" {
		gs.Key = Md5(time.Now().Format(TimeLayout) + "|" + GetRandomString(8))
	}

	//设置过期时间
	gs.UpdateCacheTime()

	return gs
}

//获取访客ID
func (gs *GuestSession) GetGuestId() string {
	return gs.Key
}

//SetSession
func (gs *GuestSession) SetSession() (err error) {
	guestId := gs.Key
	if guestId == "" {
		err = errors.New("guestId is empty")
		return
	}

	_, err = RedisConn.Do("HMSET", redis.Args{}.Add("ses."+guestId).AddFlat(gs)...)
	if err != nil {
		fmt.Println(err)
	}

	//设置过期时间
	gs.UpdateCacheTime()

	return
}

//GetSession
func (gs *GuestSession) GetSession() (err error) {
	guestId := gs.Key
	if guestId == "" {
		err = errors.New("guestId is empty")
		return
	}

	v, err := redis.Values(RedisConn.Do("HGETALL", "ses."+guestId))
	if err != nil {
		return err
	}

	err = redis.ScanStruct(v, gs)
	if err != nil {
		return err
	}

	//从数据库获取用户信息
	if gs.Uid <= 0 {
		var AL AdminLogin
		err = AL.IsLogin(guestId)
		if err != nil {
			return err
		}
		uid := AL.Uid
		var U AdminUser
		U.Id = uid
		err = U.Info()
		if err != nil {
			return err
		}

		//写入Session
		gs.Uid, gs.Name, gs.NiceName, gs.Email, gs.Phone, gs.FaceImg, gs.Status, gs.Description, gs.LastLoginIp, gs.LastLoginTime, gs.LoginFrom, gs.UserAgent =
			U.Id, U.Name, U.NiceName, U.Email, U.Phone, U.FaceImg, U.Status, U.Description, AL.LoginIp, AL.AddTime, AL.LoginFrom, AL.UserAgent

		err = gs.SetSession()
		if err != nil {
			return
		}
	}

	//设置过期时间
	gs.UpdateCacheTime()
	return
}

//检查是否登陆
func (gs *GuestSession) CheckIsLogin() bool {
	if gs.Uid <= 0 {
		return false
	}

	return true
}

//更新缓存时间
func (gs *GuestSession) UpdateCacheTime() (err error) {
	guestId := gs.Key
	if guestId == "" {
		err = errors.New("guestId is empty")
		return
	}

	_, err = RedisConn.Do("expire", "ses."+guestId, RunCFG.SessionTime)
	return
}

//清除Session
func (gs *GuestSession) Delete() (err error) {
	guestId := gs.Key
	if guestId == "" {
		err = errors.New("guestId is empty")
		return
	}

	//清除Session
	_, err = RedisConn.Do("del", "ses."+guestId)
	//重置数据
	gs = new(GuestSession)

	return
}
